﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Threading.Tasks;

namespace AzureToolkit.Domain
{
    [Export]
    public class SampleJob : IJob
    {
        [Import]
        public IAzureTable<JobRunEntity> JobRunTable { get; set; }

        [Import]
        public IAzureQueue<Command1Message> Queue1 { get; set; }

        [Import]
        public IAzureQueue<Command2Message> Queue2 { get; set; }

        public void Run()
        {
            string text = String.Format("Running task at {0}.", DateTime.UtcNow.ToUniversalTime());
            Console.WriteLine(text);

            // Add a row to the table
            JobRunTable.Add(new JobRunEntity
            {
                PartitionKey = "default",
                RowKey = Guid.NewGuid().ToString(),
                RunTime = DateTime.UtcNow,
                InstanceId = RoleEnvironment.CurrentRoleInstance.Id,
            });

            Parallel.For(0, 500, (i) =>
            {
                // Add a message to queue 1
                Queue1.AddMessageAsync(new Command1Message
                {
                    Test = text + i.ToString(),
                });

                // Add a message to queue 2
                Queue2.AddMessage(new Command2Message
                {
                    Text = text = i.ToString(),
                });
            });

        }
    }
}
